
package com.example.tests;

import java.util.concurrent.TimeUnit;

import org.junit.*;
import static org.junit.Assert.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.example.pages.InternalPage;
import com.example.pages.LoginPage;

import ru.esteru.selenium.factory.WebDriverFactory;
public class ChangeEmailTest {
  private WebDriver driver;
  private WebDriverWait wait;
  private String baseUrl;
  private StringBuffer verificationErrors = new StringBuffer();
  private LoginPage loginPage;
  private InternalPage somePage;

  @Before
  public void setUp() throws Exception {
  driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  wait = new WebDriverWait(driver, 10);
  baseUrl = "http://localhost/"; 
}

   @Test
  public void testEmailChange() {
	 goToMainPage();
	 loginAs("admin", "admin");
	 goToUserProfile();
	 changeEmailTo("admin@admin.ru");
	 assertTrue(isOnUserManagmentPage());
	 logout();
}
   
private boolean isOnUserManagmentPage() {
		return  driver.findElements(By.className("selected")).size() > 0;
}

private void changeEmailTo(String string) {
	wait.until(visibilityOfElementLocated(By.id("email"))).clear();
	wait.until(visibilityOfElementLocated(By.id("email"))).sendKeys("admin@admin.ru");
    wait.until(visibilityOfElementLocated(By.name("submit"))).click();
}

private void goToUserProfile() {
	wait.until(visibilityOfElementLocated(By.xpath("//a[contains(text(),'My profile')]")))
	.click();
}

private void logout() {
	somePage.menuLogoutLink.click();
	wait.until(alertIsPresent()).accept();
	}

private void loginAs(String username, String password) {
	loginPage.userNameField.clear();
	loginPage.userNameField.sendKeys(username);
	loginPage.passwordField.clear();
	loginPage.passwordField.sendKeys(password);
	loginPage.loginButton.click();
}

private void goToMainPage() {
driver.get(baseUrl + "/php4dvd/");
loginPage = PageFactory.initElements(driver, LoginPage.class);
somePage = PageFactory.initElements(driver, InternalPage.class);

}

  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }
}
